<template>
  <div class="xmind-home-page">
    <div class="home-page-menu" :class="{ unfold: !foldStatus, fold: foldStatus }">
      <div class="user-info-content">
        <el-popover
          :width="180"
          trigger="click"
          :show-arrow="false"
          :teleported="false"
        >
          <template #reference>
            <div class="info">
              <img :src="profile?.avatar" alt="">
              <p class="nickname">{{ profile?.nickname }}</p>
            </div>
          </template>
          <ul>
            <li @click="handleGoMindHome">
              <i class="ri-menu-fill"></i>
              <span>前往主页</span>
            </li>
            <li @click="router.push('/account')">
              <i class="ri-user-settings-line"></i>
              <span>我的账户</span>
            </li>
            <li @click="handleSignout">
              <i class="ri-logout-box-line"></i>
              <span>退出登录</span>
            </li>
          </ul>
        </el-popover>
        <div class="icon" @click="updateFoldStatus">
          <i class="ri-arrow-left-double-line"></i>
        </div>
      </div>
      <div class="menu-router-list">
        <div
          class="menu-item"
          :class="{ active: currentpath === 'recents' }"
          @click="router.push('/home/recents')">
          <el-tooltip content="最近" placement="right" :offset="28" :disabled="!foldStatus">
            <i class="ri-timer-line"></i>
          </el-tooltip>
          <p>近3天导图</p>
        </div>
        <div
          class="menu-item"
          :class="{ active: currentpath === 'sharing' }"
          @click="router.push('/home/sharing')">
          <el-tooltip content="导图分享" placement="right" :offset="28" :disabled="!foldStatus">
            <i class="ri-share-line"></i>
          </el-tooltip>
          <p>导图分享</p>
        </div>
        <div
          class="menu-item"
          :class="{ active: currentpath === 'trash' }"
          @click="router.push('/home/trash')">
          <el-tooltip content="回收站" placement="right" :offset="28" :disabled="!foldStatus">
            <i class="ri-delete-bin-6-line"></i>
          </el-tooltip>
          <p>回收站</p>
        </div>
      </div>
      <div class="collect-xmind" :class="{ fold: !collectUnFold, unfold: collectUnFold }">
        <p class="title"><i class="ri-arrow-down-s-fill" @click="collectUnFold = !collectUnFold"></i>收藏</p>
        <div class="modal" v-show="collectUnFold">
          <el-scrollbar max-height="300px">
            <div class="list" v-if="!!collectMindList.length">
              <div class="item" v-for="item in collectMindList" :key="item.id" @click="handleMindMapClick(item.id)">
                <el-popover placement="right" :width="300" popper-class="preview-cover-popover" :show-arrow="false">
                  <div>
                    <div class="img">
                      <img :src="item.coverImage" alt="">
                    </div>
                    <p>
                      {{ item.name }}
                      <span class="update-time">最近修改时间：{{ item.updateTime }}</span>
                    </p>
                  </div>
                  <template #reference>
                    <div>
                      <img src="@/assets/images/home/mind.png" alt="">
                      <span class="name">{{ item.name }}</span>
                    </div>
                  </template>
                </el-popover>
              </div>
            </div>
            <div class="tip" v-else>点击导图上的星号添加收藏</div>
            </el-scrollbar>
          </div>
        <el-tooltip content="收藏" placement="right" :offset="28" :disabled="!foldStatus">
          <div class="icon"><i class="ri-star-line"></i></div>
        </el-tooltip>
      </div>
      <div class="menu-router-list" style="padding-top: 12px;">
        <div
          class="menu-item"
          :class="{ active: currentpath === 'work' }"
          @click="router.push('/home/work')">
          <el-tooltip content="我的导图" placement="right" :offset="28" :disabled="!foldStatus">
            <i class="ri-stack-line"></i>
          </el-tooltip>
          <p>我的导图</p>
        </div>
      </div>
    </div>
    <div class="home-page-content">
      <header class="container-head">
        <div class="page-title bread-crumbs" v-if="['work', 'trash'].includes(currentpath)">
          <p v-for="(item, index) in workBreadCrumbs" :key="index">
            <span @click="handleClickBreadCrumb(item, index)">{{ item.title }}</span>
            <i class="ri-arrow-right-s-line" v-show="index < workBreadCrumbs.length - 1"></i>
          </p>
        </div>
        <div class="page-title" v-else>{{ optionPageConfig[currentpath].pageName }}</div>
        <div class="right-operate-plan">
          <div v-if="optionPageConfig[currentpath].add">
            <el-button type="primary" :loading="createMindLoading" @click="handleCreateMind">新建导图</el-button>
          </div>
          <div v-if="optionPageConfig[currentpath].search">
            <el-input
              v-model="searchKeywords"
              style="width: 240px"
              placeholder="搜索导图和文件夹"
              :prefix-icon="Search"
              clearable
              @keyup.enter.stop="handleSearchBykeywords"
            />
          </div>
          <div class="list-show-type" v-if="optionPageConfig[currentpath].grid">
            <div class="tab" :class="{ active: grid === 'card' }" @click="grid = 'card'"><i class="ri-gallery-view-2"></i></div>
            <div class="tab" :class="{ active: grid === 'list' }" @click="grid = 'list'"><i class="ri-list-check"></i></div>
          </div>
          <el-radio-group v-if="optionPageConfig[currentpath].shareType" v-model="shareType" @change="handleShareTypeChange">
            <el-radio-button label="与我分享" :value="1" />
            <el-radio-button label="我的分享" :value="2" />
          </el-radio-group>
        </div>
      </header>
      <div class="content">
        <router-view :key="route.params.id" :grid="grid" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import mitter from '@/mitt'
import { userStore } from '@/store/user.store'
import { commonStore } from '@/store/common.store'
import { handleSignout } from '@/utils/common'
import { apiGetUserCollectList, apiCreateMind } from '@/apis/work'
import { initXmindMapJson } from '@/pages/mind-map/config'
import type { HomeConfigOptions, BreadCrumb, Mind } from '@/types'

const [route, router] = [useRoute(), useRouter()]
const optionPageConfig = reactive<HomeConfigOptions>({
  recents: {
    pageName: '近三天导图',
    search: true,
    add: true,
    grid: true,
    shareType: false
  },
  sharing: {
    pageName: '导图分享',
    search: true,
    add: false,
    grid: false,
    shareType: true
  },
  trash: {
    pageName: '回收站',
    search: true,
    add: false,
    grid: true,
    shareType: false
  },
  work: {
    pageName: '我的导图',
    search: true,
    add: true,
    grid: true,
    shareType: false
  }
})
const shareType = ref(1)
const { profile } = storeToRefs(userStore())
const { updateFoldStatus } = commonStore()
const { workBreadCrumbs, foldStatus } = storeToRefs(commonStore())

const searchKeywords = ref('')
const grid = ref<'card' | 'list'>('card')

const currentpath = ref<keyof HomeConfigOptions>('recents')
watch(() => route.fullPath, newVal => {
  currentpath.value = newVal.split('/')[2] as keyof HomeConfigOptions
  searchKeywords.value = ''
  shareType.value = 1
}, { deep: true, immediate: true })

const collectUnFold = ref(true)

const createMindLoading = ref(false)
/**
 * 导图创建
 */
const handleCreateMind = async () => {
  if (createMindLoading.value) return
  createMindLoading.value = true
  try {
    const mindJson = [initXmindMapJson()]
    const mindId = await apiCreateMind({ name: '我的导图', mindJson })
    router.push(`/mind-map/${mindId}`)
  } finally {
    createMindLoading.value = false
  }
}

const handleGoMindHome = () => {
  window.location.href = '/'
}

const handleSearchBykeywords = () => {
  mitter.emit('search-mind-list', searchKeywords.value)
}

const handleClickBreadCrumb = (breadCrumb: BreadCrumb, idx: number) => {
  if (idx === workBreadCrumbs.value.length - 1) return
  mitter.emit('bread-crumb-click', breadCrumb)
}

const collectMindList = ref<Mind[]>([])
const queryUserCollectMindList = async () => {
  const data = await apiGetUserCollectList<Mind[]>()
  collectMindList.value = data
}
queryUserCollectMindList()

const handleMindMapClick = (mindId: string) => {
  router.push(`/mind-map/${mindId}`)
}

const handleShareTypeChange = (shareType: 1 | 2) => {
  mitter.emit('share-type-change', shareType)
}

mitter.on('refresh-collect-list', () => {
  queryUserCollectMindList()
})

onBeforeUnmount(() => {
  mitter.off('bread-crumb-click')
  mitter.off('search-mind-list')
  mitter.off('refresh-collect-list')
})
</script>

<style lang="scss" scoped>
.xmind-home-page {
  height: 100vh;
  display: flex;
  .home-page-menu {
    background-color: #FAFAFB;
    border-right: 1px solid rgba(0, 0, 0, .05);
    transition: .3s;
    height: 100%;
    &.unfold {
      width: 226px;
    }
    &.fold {
      width: 60px;
      overflow: hidden;
      .menu-router-list {
        .menu-item {
          p {
            display: none;
          }
        }
      }
      .user-info-content {
        flex-direction: column-reverse;
        align-items: center;
        justify-content: center;
        .info {
          margin-top: 15px;
          width: auto;
          .nickname {
            display: none;
          }
        }
        .icon {
          transform: rotate(180deg);
          margin-left: 4px;
        }
      }
      .collect-xmind {
        padding: 10px 0 10px 10px;
        cursor: pointer;
        .title, .modal {
          display: none !important;
        }
        .icon {
          display: inline-block;
          margin-left: 4px;
          padding: 6px;
          border-radius: 4px;
          &:hover {
            background-color: rgba(0, 0, 0, .05);
          }
        }
      }
    }
    .user-info-content {
      padding: 20px 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid rgba(0, 0, 0, .05);
      .info {
        display: flex;
        align-items: center;
        font-size: 0;
        flex: 1;
        width: 0;
        cursor: pointer;
        padding: 6px 8px;
        border-radius: 6px;
        &:hover {
          background-color: #e1e1e1;
        }
        img {
          width: 30px;
          height: 30px;
          object-fit: cover;
          border-radius: 50%;
        }
        .nickname {
          color: #27292a;
          font-size: 13px;
          margin-left: 6px;
          flex: 1;
          width: 0;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          line-height: 22px;
        }
      }
      :deep(.el-popper) {
        padding: 12px 8px;
      }
      ul {
        li {
          padding: 8px 6px;
          border-radius: 6px;
          cursor: pointer;
          display: flex;
          align-items: center;
          color: #333;
          & + li {
            margin-top: 4px;
          }
          &:hover {
            background-color: #e1e1e1;
          }
          i {
            font-size: 18px;
            position: relative;
            top: 1px;
          }
          span {
            font-size: 14px;
            margin-left: 6px;
          }
        }
      }
      .icon {
        color: #999;
        padding: 2px 3px;
        border-radius: 4px;
        font-size: 0;
        cursor: pointer;
        transition: 0.3s;
        &:hover {
          background-color: #f1f1f1;
        }
        i {
          font-size: 20px;
        }
      }
    }
    .menu-router-list {
      padding: 24px 12px 12px;
      border-bottom: 1px solid rgba(0, 0, 0, .05);
      .menu-item {
        display: flex;
        align-items: center;
        height: 34px;
        color: #27292a;
        border-radius: 4px;
        padding: 0 8px;
        cursor: pointer;
        &.active, &:hover {
          background-color: rgba(0, 0, 0, .05);
        }
        & + .menu-item {
          margin-top: 6px;
        }
        p {
          margin-left: 6px;
          font-size: 13px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          flex: 1;
          width: 0;
        }
        i {
          font-size: 20px;
        }
      }
    }
    .collect-xmind {
      padding: 16px;
      border-bottom: 1px solid rgba(0, 0, 0, .05);
      &.fold {
        .title {
          i {
            transform: rotate(-90deg);
          }
        }
      }
      &.unfold {
        .modal {
          margin-top: 12px;
        }
      }
      .title {
        color: #000;
        font-weight: 600;
        font-size: 14px;
        position: relative;
        padding-left: 6px;
        i {
          position: absolute;
          left: -12px;
          top: 3px;
          color: #333;
          cursor: pointer;
          transition: 0.3s;
        }
      }
      .list {
        .item {
          padding: 8px 0;
          font-size: 14px;
          padding-left: 6px;
          border-radius: 4px;
          & + .item {
            margin-top: 2px;
          }
          cursor: pointer;
          &:hover {
            background-color: rgba(0, 0, 0, .05);
          }
          & > div {
            display: flex;
            align-items: center;
          }
          img {
            width: 24px;
            margin-right: 6px;
            margin-left: -4px;
          }
          span {
            color: #333;
            flex: 1;
            width: 0;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
      .tip {
        color: #999;
        font-size: 11px;
        padding-left: 6px;
        font-weight: 500;
        white-space: nowrap;
      }
      .icon {
        font-size: 20px;
        display: none;
        i {
          display: block;
        }
      }
    }
  }
  .home-page-content {
    flex: 1;
    width: 0;
    display: flex;
    flex-direction: column;
    .container-head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24px 32px 8px 60px;
      .page-title {
        font-size: 24px;
        color: #27292a;
        font-weight: 600;
        cursor: default;
        user-select: none;

        &.bread-crumbs {
          display: flex;
          align-items: center;
          p {
            margin-right: 5px;
            span {
              cursor: pointer;
            }
            i {
              margin-left: 4px;
            }
          }
        }
      }
      .right-operate-plan {
        display: flex;
        align-items: center;
        & > div {
          margin: 0 6px;
        }
        .list-show-type {
          display: flex;
          position: relative;
          padding-right: 10px;
          &:after {
            content: "";
            position: absolute;
            width: 1px;
            top: 9px;
            bottom: 7px;
            background-color: rgba(0, 0, 0, .1);
            right: 0;
          }
          .tab {
            padding: 5px 7px;
            border-radius: 4px;
            cursor: pointer;
            & + .tab {
              margin-left: 6px;
            }
            &.active, &:hover {
              background-color: rgba(0, 0, 0, .05);
            }
            i {
              font-size: 22px;
              color: #27292a;
            }
          }
        }

        :deep(.el-radio-button__inner) {
          padding: 7px 12px;
        }
      }
    }
    .content {
      height: 0;
      flex: 1;
      padding: 24px 32px 8px 60px;
      overflow-y: scroll;
    }
  }
}
</style>

<style lang="scss">
.preview-cover-popover {
  padding: 0 !important;
  & > div {
    .img {
      font-size: 0;
      border-bottom: 1px solid rgba(0, 0, 0, .08);
      aspect-ratio: 2.05;
      overflow: hidden;
      border-radius: 8px 8px 0 0;
      img {
        width: 100%;
        height: 100%;
        -o-object-fit: cover;
        object-fit: cover;
        max-width: 100%;
        display: block;
        transition: 0.3s;
      }
    }
    p {
      color: #333;
      padding: 8px 15px;
      font-size: 12px;
      span {
        color: #999;
        font-size: 10px;
        display: block;
        margin-top: 4px;
      }
    }
  }
}
</style>
